package com.cn.sys.frame.util.page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cn.sys.common.Constants;

/**
 * 分页类
 * @author liuwenjie
 *
 * @param <T>
 */
public class PageData<T> {

	private int pageNumber; //当前页数
	private List<T> pageItems = new ArrayList<T>(); //当前页面数据
	private int pageSize; //每页显示的记录数
	private long totalCount; //记录总数

	private long startOffset;//开始索引
	private long endOffset;//结束索引
	
	public long getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(long totalCount) {
		this.totalCount = totalCount;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public void setPageItems(List<T> pageItems) {
		this.pageItems = pageItems;
	}

	public int getPageNumber() {
		if(pageNumber<=0){
			pageNumber = (int) (this.getStartOffset() / this.pageSize );
		}
		return pageNumber;
	}

	public List<T> getPageItems() {
		return pageItems;
	}

	public int getPageSize() {
		if(this.pageSize <=0 ){
			pageSize = Constants.DEFAULT_PAGE_SIZE;
		}
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public long getStartOffset() {
		if(pageNumber > 0 && pageSize > 0){
			startOffset = (long) pageSize * (pageNumber - 1);
		}
		return startOffset;
	}
	public void setStartOffset(long startOffset) {
		this.startOffset = startOffset;
	}
	public long getEndOffset() {
		endOffset = this.getStartOffset() + this.getPageSize();
		if (endOffset>totalCount) {
			endOffset = totalCount;
		}
		return endOffset;
	}
	public void setEndOffset(int endOffset) {
		this.endOffset = endOffset;
	}
	
	public Map<String, Object> getPageDataMap(){
		Map<String, Object> result = new HashMap<String, Object>(2);
		if(getPageItems()!=null&&!getPageItems().isEmpty()){
			result.put("rows", getPageItems());
		}else {
			result.put("rows", new ArrayList<Object>(0));
		}
		if(getTotalCount()>0){
			result.put("total", getTotalCount());
		}else {
			result.put("total", 0);
		}
		return result;
	}
}
